from fastapi import FastAPI
from fastapi.responses import ORJSONResponse
from src.config import settings
from src.log import logger
from src.core.register import (
    on_lifespan,
    register_router,
    register_system_router,
    register_static,
    register_middleware,
    register_exception,
    register_db,
)


def create_app() -> FastAPI:
    """
    启动项目
    docs_url：配置交互文档的路由地址，如果禁用则为None，默认为 /docs
    redoc_url： 配置 Redoc 文档的路由地址，如果禁用则为None，默认为 /redoc
    openapi_url：配置接口文件json数据文件路由地址，如果禁用则为None，默认为/openapi.json
    """
    host = str(settings.FASTAPI_CONFIG.HOST)
    port = settings.FASTAPI_CONFIG.PORT
    server_address = f"http://{'127.0.0.1' if host == '0.0.0.0' else host}:{port}"

    serving_str = f"\nAPI Server URL:http://{host}:{port}"
    serving_str += f"\nSwagger UI Docs:{server_address}/docs"
    serving_str += f"\nRedoc HTML Docs:{server_address}/redoc"
    logger.info(serving_str)

    app = FastAPI(
        # debug=settings.system.DEBUG,
        title=settings.FASTAPI_CONFIG.TITLE,
        version=settings.FASTAPI_CONFIG.VERSION,
        description=settings.FASTAPI_CONFIG.DESCRIPTION,
        lifespan=on_lifespan,
        default_response_class=ORJSONResponse,
        docs_url=None,
        redoc_url=None,
        servers=[{"url": "http://127.0.0.1:9000", "description": "开发环境"}],
    )
    # app.router.route_class = LoggingRoute
    # 初始化数据库
    register_db(app)
    # 全局异常捕捉处理
    register_exception(app)

    # 注册中间件
    register_middleware(app)

    # 挂在静态目录
    register_static(app)

    # 引入应用中的路由
    register_router(app)

    # 加载系统路由
    register_system_router(app)
    return app
